package logic

import (
	"common/global"
	"common/model"
	"context"
	"errors"
	"github.com/go-redis/redis/v8"
	"product_server/dao/dao_redis"
	product "product_server/proto"
)

func (p *ProductServer) ProductCreateCat(ctx context.Context, req *product.ProductCreateCatRequest) (*product.ProductCreateCatResponse, error) {
	err := global.Client.Watch(context.Background(), func(tx *redis.Tx) error {
		//商品是否存在
		info, err := model.GetProductInfo(req.ProductId)
		if err != nil {
			return errors.New("商品信息查询失败")
		}
		//商品库存判断
		if req.Num > info.Stock && info.Stock <= 0 {
			return errors.New("商品库存不足")
		}
		//购物车是否存在
		if !dao_redis.GetCatExists(req.Uid, info.Id) {
			//加入购物车
			err = dao_redis.HSetProduct(info, req.Uid, req.Num)
			if err != nil {
				return errors.New("商品加入购物车失败")
			}
		} else {
			//购物车商品自增
			err = dao_redis.CatProductIncr(req.Uid, req.Num, info.Id)
			if err != nil {
				return errors.New("购物车商品增加失败")
			}
		}
		return nil
	})
	if err != nil {
		return nil, errors.New("redis事务启动失败")
	}
	return &product.ProductCreateCatResponse{Success: true}, nil
}
